package com.wnxy.sddfp.common.exception;


import com.wnxy.sddfp.common.result.Result;
import com.wnxy.sddfp.common.result.enums.impl.ResultCode;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalException {

    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public Result handlerBusinessException(BusinessException e) {
        e.printStackTrace();
        return Result.fail(e.getErrorCode().getCode(),e.getErrorCode().getMessage());
    }

    // 非法参数异常
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handlerException(IllegalArgumentException e) {
        e.printStackTrace();
        return Result.fail(ResultCode.PARAM_IS_INVALID);
    }

    // 参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handlerArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        Map<String, String> map = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return Result.fail(ResultCode.PARAM_IS_BLANK,map);
    }

    // 当其他错误类型都不匹配的时候执行
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e) {
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }
}
